const url = '/block/query/latest';
import store from "../utils/store";
import request from "@/utils/request";

let ignore = false;
let timeout=null;

export default function main(subFun) {
    if (!subFun) return;
    ignore = false;
    clearInterval(timeout);
    let old = store.get('blockHeight');
    if (old) {
        subFun(old);
    }
    const got = () => {
        request
            .get(url)
            .then(t => {
                if (t.msg != 'ok' || !t.data) {
                    return;
                }
                store.set('blockHeight', t.data);
                subFun(t.data);
            })
            .catch(e => {
                console.log(e);
            });
    };
    timeout=setInterval(got, 6000);
    got();
    return () => {
        ignore = true;
        clearInterval(timeout);
        console.log('unsub');
    }
}

// export default function main(subFun) {
//     console.log('*************start sub block height**************');
//     if (!subFun) return;
//     let old=store.get('blockHeight');
//     if(old){
//         console.log('*************has cache**************');
//         subFun(old);
//     }
//     const source = new EventSource(url);
//     source.onopen = function (event) {
//         console.log('EventSource is open');
//     };
//     source.onclose = function (event) {
//         console.log('EventSource is close');
//     };
//     source.onmessage = function (event) {
//         // console.log("EventSource onmessage");
//         const d = JSON.parse(event.data);
//         store.set('blockHeight',d);
//         subFun(d);
//     };
//     source.onerror = function (event) {
//         console.log("EventSource error ", event);
//     };
//     return () => {
//         console.log('unsub');
//         source.close();
//     }
// }